<template>
  <div class="adminEbook">
    <a-layout>
      <a-layout-content
          :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
      >

        <p class="adminEbookHeader">
          <a-form layout="inline" :model="searchEbook">
            <a-form-item>
              <a-input v-model:value="searchEbook.name" placeholder="请输入想查询的名称">
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-button  @click="handleQueryByName({page: 1, size: pagination.pageSize})" shape="round">
                <SearchOutlined />
              </a-button>
            </a-form-item>
            <a-form-item>
              <a-button  @click="add()" shape="round">
                <book-outlined />
                扩充知识库
              </a-button>
            </a-form-item>
          </a-form>
        </p>

        <a-table
            :data-source="ebooks"
            :columns="columns"
            :row-key="record => record.id"
            :pagination="pagination"
            :loading="loading"
            @change="handleTableChange">

          <template #cover="{ text: cover }">
            <img class="coverImg" v-if="cover" :src="cover" alt="avatar " />
          </template>
          <template v-slot:category="{ text, record }">
            <span>{{ getCategoryName(record.category1Id) }} / {{ getCategoryName(record.category2Id) }}</span>
          </template>
          <template v-slot:action="{ text, record }">
            <a-space size="small">
              <router-link :to="'/admin/doc?ebookId='+record.id">
                <a-button shape="round" >
                  <file-text-outlined />
                  文档管理
                </a-button>
              </router-link>

              <a-button  @click="edit(record)" shape="round">
                <edit-outlined />
                编辑
              </a-button>
              <a-popconfirm
                  title="确定要删除这个记录吗？"
                  ok-text="是的"
                  cancel-text="不是"
                  @confirm="handleDelete(record.id)"
              >
                <a-button  shape="round">
                  <delete-outlined />
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table>
      </a-layout-content>
    </a-layout>
  </div>
  <a-modal
      title="知识库表单"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
  >
    <a-form :model="ebook" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="封面">
        <a-input v-model:value="ebook.cover" />
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name" />
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader
            v-model:value="categoryIds"
            :field-names="{ label: 'name', value: 'id', children: 'children' }"
            :options="level1"
        />
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="ebook.description" type="textarea" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, onMounted,ref } from 'vue';
import axios from 'axios';
import { message } from "ant-design-vue";
import { Tool } from '@/util/tool';

export default defineComponent({
  name:'AdminEbook',
  setup() {
    // 定义响应式变量searchEbook
    const searchEbook = ref();
    searchEbook.value={};
    const ebooks = ref();
    const pagination = ref({
      current: 1,
      pageSize: 10,
      total: 0
    });
    const loading = ref(false);

    const columns = [
      {
        title: '封面',
        dataIndex: 'cover',
        slots: {customRender: 'cover'}
      },
      {
        title: '知识名称',
        dataIndex: 'name',
      },
      {
        title: '知识分类',
        slots: { customRender: 'category' }
      },
      {
        title: '总文档数',
        dataIndex: 'docCount',

      },
      {
        title: '总阅读数',
        dataIndex: 'viewCount',
      },
      {
        title: '总点赞数',
        dataIndex: 'voteCount',
      },
      {
        title: '',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];
    /**
     * 数据查询,前后端分页同步
     **/
    const handleQuery = (params: any) => {
      loading.value = true;
      // 如果不清空现有数据，则编辑保存重新加载数据后，再点编辑，则列表显示的还是编辑前的数据
      // ebooks.value = [];
      axios.get("/ebook/list",({
        params:{
          page:params.page,
          size:params.size,
          name:searchEbook.value.name
        }
      })).then((response) =>{
        console.log(1111)
        loading.value=false;
        const data = response.data;
        if (data.success){
          ebooks.value= data.content.list;

          // 重置分页按钮
          pagination.value.current = params.page;
          pagination.value.total = data.content.total;
        }else {
          message.error(data.message);
        }
      });
    };

    const handleTableChange = (pagination: any) => {
      console.log("看看自带的分页参数都有啥：" + pagination);
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize
      });
    };



    // -------表单--------
    /**
     * 数组，[100, 101]对应：前端开发 / Vue
     */
    const categoryIds = ref();
    const ebook= ref();
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const handleModalOk = () => {
      // 点击ok先显示loading效果
      modalLoading.value = true;
      ebook.value.category1Id = categoryIds.value[0];
      ebook.value.category2Id = categoryIds.value[1];
      axios.post("/ebook/save", ebook.value).then((response) => {

        modalLoading.value = false;
        // 当post请求发送以后，值返回时执行以下操作
        const data = response.data;
        if (data.success){ // data = CommonResp,所以有success属性
          // 如果保存成功，取消loading效果，关闭对话框

          modalVisible.value = false;

          // 关闭对话框后重新加载列表
          handleQuery({
            page:pagination.value.current, // 加载当前所在页
            size:pagination.value.pageSize
          })
        }else {
          message.error(data.message);
        }

      });
    };


    // 编辑功能，点击编辑按钮时触发的事件
    const edit = (record:any) => {
      // 显示模态框
      modalVisible.value = true;
      ebook.value = record;
      categoryIds.value = [ebook.value.category1Id, ebook.value.category2Id]
    };

    // 新增功能，点击新增按钮时触发的事件
    const add = () => {
      modalVisible.value = true;
      ebook.value = {}
    };

    const level1 =  ref();
    let categorys: any;
    /**
     * 查询所有分类，返回分类的所有信息
     **/
    const handleQueryCategory = () => {
      loading.value = true;
      axios.get("/category/all").then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          categorys = data.content;
          console.log("原始数组：", categorys);

          level1.value = [];
          level1.value = Tool.array2Tree(categorys, 0);
          // 让分类查询在表格数据查询之前执行 否则在表格数据渲染时可能会出现分类数据为空情况（因为获取电子书数据和获取分类信息是异步的）
          handleQuery({
            page: 1,
            size: pagination.value.pageSize,
          });
          console.log("树形结构：", level1.value);
        } else {
          message.error(data.message);
        }
      });
    };

    // 删除功能，点击删除按钮时触发的事件
    const handleDelete = (id:number) =>{
      axios.delete("/ebook/delete/"+ id).then((response) => {

        // 当delete请求发送以后，值返回时执行以下操作
        const data = response.data;
        if (data.success){ // data = CommonResp,所以有success属性
          // 如果删除成功，直接重新加载列表
          handleQuery({
            page:pagination.value.current, // 加载当前所在页
            size:pagination.value.pageSize
          })
        }
      });
    };

    /**
     * 根据name查询电子书信息
     */
    const handleQueryByName = (params: any) => {
      loading.value = true;
      ebooks.value = [];
      axios.get("/ebook/search", {
        params: {
          page: params.page,
          size: params.size,
          name: searchEbook.value.name
        }
      }).then((response) => {

        loading.value = false;
        const data = response.data;
        if (data.success) {
          ebooks.value = data.content.list;
          // 重置分页按钮
          pagination.value.current = params.page;
          pagination.value.total = data.content.total;
        } else {
          message.error(data.message);
        }

      })
    };

    // 通过id来获取分类的名字
    const getCategoryName = (cid: number) => {
      // console.log(cid)
      let result = "";
      categorys.forEach((item: any) => {
        // 注意是item.id == cid，不是===
        if (item.id == cid) {
          // return item.name; // 注意，这里直接return不起作用
          result = item.name;
        }
      });
      return result;
    };

    onMounted(()=>{
      handleQueryCategory();
    })

    return{
      // 表格用到的返回参数
      ebooks,
      pagination,
      columns,
      loading,
      handleTableChange,
      getCategoryName,

      // 新增和编辑
      edit,
      add,

      // 表单用到的返回参数
      ebook,
      modalVisible,
      modalLoading,
      handleModalOk,
      categoryIds,
      level1,

      handleDelete,

      //搜索功能用到的返回参数
      handleQueryByName,
      searchEbook
    }
  },
});
</script>
<style scoped>
.adminEbook{
  text-align: center;
  margin: 15px 200px 10px;
}
.adminEbookHeader{
  margin: 15px 310px 10px;

}
.coverImg {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 15%;
  margin: 5px 0;

}
</style>
